from sqlalchemy import Column,Integer,String
from factory import DBConnection
from model import Base

class User(Base):
    __tablename__ = 'user'
    id = Column('id',Integer,primary_key=True,unique=True)
    userName = Column('user_name',String,nullable=False)
    password = Column('password',String,nullable=False)

    __columnList = ['id','userName','password']

    def toDict(self):
        print('id:',self.id,'userName:',self.userName,'password:',self.password)

    def toJson(self):
        result = {}
        result['id'] = self.id
        result['userName'] = self.userName
        result['password'] = self.password
        return result

    @staticmethod
    def login(userName,password):
        session = DBConnection.getSession()
        user = session.query(User).filter(User.userName == userName,User.password == password).first()
        return user is None

    @staticmethod
    def queryAllUsers():
        """
        查询所有的用户
        :return:
        """
        userListJson = []
        session = DBConnection.getSession()
        userList = session.query(User).all()
        for user in userList:
            userListJson.append(user.toJson())
        session.close()
        return userListJson

    @staticmethod
    def queryAllUsersByPage(**kwargs):
        """
        根据条件分页查询某些列，支持模糊查询
        :param kwargs:
        :return:
        """
        userName = kwargs['userName']
        pageSize = kwargs['pageSize']
        currentPage = kwargs['currentPage']
        session = DBConnection.getSession()

        #查询的某些列返回的是元组 ('liaokailei', '123456')
        userList = session.query(User.userName,User.password).filter(User.userName.like('%' + userName + '%')).limit(pageSize).offset((currentPage - 1) * pageSize)
        for user in userList:
            print(user)

